package org.example;

import org.apache.sshd.client.SshClient;
import org.apache.sshd.client.channel.ClientChannel;
import org.apache.sshd.client.channel.ClientChannelEvent;
import org.apache.sshd.client.session.ClientSession;
import org.w3c.dom.ls.LSOutput;

import java.io.IOException;
import java.util.EnumSet;

/**
 * 用途
 *
 * @author deng
 * @date 2022/1/22 9:43
 */
public class SShd {


    /**
     * 这个是交互式客户端
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        long timeout = 60000;
        SshClient client = SshClient.setUpDefaultClient();

        client.start();

        // using the client for multiple sessions...
        try (ClientSession session = client.connect("root", "192.168.133.180", 22)
                .verify(timeout)
                .getSession()) {
            session.addPasswordIdentity("newlandedu@123"); // for password-based authentication
            // or
            // session.addPublicKeyIdentity(...key-pair...); // for password-less authentication
            // Note: can add BOTH password AND public key identities - depends on the client/server security setup

            session.auth().verify(timeout);
            // Assuming one has obtained a ClientSession as already shown
            try (ClientChannel channel = session.createShellChannel(/* use internal defaults */)) {
                channel.setIn(System.in);
                channel.setOut(System.out);
                channel.setErr(System.err);
                // ... spawn the thread(s) that will pump the STDIN/OUT/ERR
                try {
                    channel.open().verify( timeout);
                    // Wait (forever) for the channel to close - signalling shell exited
                    channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), 0L);
                } finally {
                    // ... stop the pumping threads ...
                }
            }
            // start using the session to run commands, do SCP/SFTP, create local/remote port forwarding, etc...
        }


// exiting in an orderly fashion once the code no longer needs to establish SSH session
// NOTE: this can/should be done when the application exits.
        client.stop();
    }
}
